package com.liwei.controller;

import com.liwei.beans.Stu;
import com.liwei.services.StuServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Controller
@RequestMapping("/stu")
public class StuController {
    @Autowired
    StuServices stuServices;

    @RequestMapping("getAll.action")
    public String getAll(Model model) {
        ArrayList<Stu> all = stuServices.getAll();
        model.addAttribute("stus", all);
        return "stuView";
    }

    //@RequestMapping(value = "add.action",method = {RequestMethod.GET,RequestMethod.POST})
    @RequestMapping("add.action")
    public String add(/*HttpServletRequest req, HttpServletRequest resp,*/Model model, Stu stu) {
        /*String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String score = req.getParameter("score");
        Float scoreFloat=Float.parseFloat(score);

        Stu stu = new Stu();
        stu.setName(name);
        stu.setAge(age);
        stu.setSex(sex);
        stu.setScore(scoreFloat);*/
        boolean add = stuServices.add(stu);
        if (!add) {
            model.addAttribute("mess", "添加没有影响任何行数");
            //forward有视图解析器，因此直接返回文件名即可
            return "mess";
        }
        //重定向，是HttpServletRequest对象的sendRedirect方法,没有视图解析器
        return "redirect:/stu/getAll.action";
    }

    //如果前后端参数不一致可以使用@RequestParam(value = "id")来修改前端参数
    @RequestMapping("del.action")
    public String del(Model model,/*@RequestParam(value = "id")*/ int id) {
        boolean del = stuServices.del(id);
        if (!del) {
            model.addAttribute("mess", "添加没有影响任何行数");
            //forward有视图解析器，因此直接返回文件名即可
            return "mess";
        }
        //重定向，是HttpServletRequest对象的sendRedirect方法,没有视图解析器
        return "redirect:/stu/getAll.action";
    }
    //按照id查询数据,给修改界面显示
    @RequestMapping("get.action")
    public String get(Model model,/*@RequestParam(value = "id")*/ int id) {
        Stu stu = stuServices.get(id);
        model.addAttribute("stu", stu);
        //forward有视图解析器，因此直接返回文件名即可
        return "stuEdit";
    }
    @RequestMapping("edit.action")
    public String edit(Model model,Stu stu) {
        boolean edit = stuServices.edit(stu);
        if (!edit){
            model.addAttribute("mess", "修改没有影响任何行数");
            //forward有视图解析器，因此直接返回文件名即可
            return "mess";
        }
        //重定向，是HttpServletRequest对象的sendRedirect方法,没有视图解析器
        return "redirect:/stu/getAll.action";
    }

}
